package com.io.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Scanner;

public class ChatClient {

    private String host="127.0.0.1";
    private int port=9879;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        NioEventLoopGroup clientLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(clientLoopGroup)
                    //客户端的通道类型（是一个实现类）
                    .channel(NioSocketChannel.class)
                    //不管是客户端还是服务器端，这里面的泛型都是用来传递数据的通道:SocketChannel接口
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //得到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入相关handler
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自定义的handler
                            pipeline.addLast(new ChatClientHandler());
                        }
                    });

            //得到连接服务器的ChannelFuture对象，这里是用的同步的
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //得到连接服务器的通道
            Channel channel = channelFuture.channel();
            //上面连接服务器时的同步设置（sync）就是是为了启动客户端时可以输出自己的信息
            System.out.println("-------" + channel.localAddress()+ "--------");
            //客户端需要输入信息，创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                //通过channel 发送到服务器端
                //如果不是同步，那么可能通道还没连接服务端，这里发送信息肯定会失败，但是如果是同步
                //上面就会一直等待服务端的连接，效率不是又低了吗？这里有点不理解
                //是同步的，客户端一直在等待，连接成功之后，才会往下执行
                channel.writeAndFlush(msg + "\r\n");
            }
        }finally {
            clientLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception{
        new ChatClient("127.0.0.1",9879).run();
    }
}
